import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Input, Button, Table, message, TreeSelect, Select, Checkbox, Space } from 'antd'
import _ from 'loadsh'
import { addWindow } from '@redux/actions'
import style from '../filingCaseManage/CaseManage.module.less'
import { compressLicenseAndMobile, confirmAction } from '@src/assets/js/tool'
import { DownloadOutlined } from '@ant-design/icons'
import { json2Excel } from '@src/assets/js/excel'

const { Item } = Form
const { Option } = Select
const layout = {
  labelCol: { flex: '80px' }
}

// 获取表格字段配置
function getColumns () {
  const list = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '姓名',
      dataIndex: 'name',
      width: 100
    },
    {
      title: '专业',
      dataIndex: 'professional',
      key: 'professional',
      width: 200
    },
    {
      title: '单位',
      dataIndex: 'structure',
      width: 200
    },
    {
      title: '职业分类',
      dataIndex: 'occupation',
      width: 120
    },
    {
      title: '擅长专业',
      dataIndex: 'special',
      width: 250
    },
    {
      title: '总办',
      dataIndex: 'caseon_all',
      width: 100,
      align: 'center'
    },
    {
      title: '在办',
      dataIndex: 'caseing',
      width: 100,
      align: 'center'
    },
    {
      title: '今年总办',
      dataIndex: 'caseon',
      sorter: true,
      width: 150,
      align: 'center'
    },
    {
      title: '首',
      dataIndex: 'caseon1',
      sorter: true,
      width: 100,
      align: 'center'
    },
    {
      title: '独',
      dataIndex: 'caseon2',
      sorter: true,
      width: 100,
      align: 'center'
    },
    {
      title: '边',
      dataIndex: 'caseon3',
      sorter: true,
      width: 100,
      align: 'center'
    }
  ]
  if (this.state.actions) {
    list.splice(5, 0, {
      title: '同案由',
      dataIndex: 'cause_action_count',
      sorter: true,
      width: 130,
      align: 'center'
    })
  }
  return list
}

class ArbitratorCaseStatistic extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    areaOptions: ['哈尔滨市', '齐齐哈尔市', '牡丹江市', '佳木斯市', '大庆市', '鸡西市', '双鸭山市', '鹤岗市', '七台河市', '伊春市', '黑河市', '绥化市', '大兴安岭地区', '外地', '外籍'],
    detailAreaOptions: [],
    areaMap: {},
    occupationMap: {},
    detailAreaVisible: false,
    areaIndeterminate: false,
    areaCheckAll: true,
    areaCheckedList: [],
    typeOptions: [],
    typeIndeterminate: false,
    typeCheckAll: true,
    typeCheckedList: [],
    majors: [],
    detailData: null,
    detailVisible: false,
    orderField: '',
    order: '',
    actions: undefined,
    treeData: [],
    condition: []
  }

  formRef = React.createRef()

  detailFormRef = React.createRef()

  // 改变案件状态
  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  searchHandle (d) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData(d)
    })
  }

  // 获取搜索条件
  getParams (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination, status, typeCheckedList, areaMap, orderField, order } = this.state
    let areaCheckedList = this.state.areaCheckedList.slice()
    const { current, pageSize } = pagination
    form = form || this.formRef.current.getFieldsValue()
    const condition = []
    if (areaCheckedList.length) {
      const otherIndex = areaCheckedList.indexOf('外地')
      if (otherIndex !== -1) {
        areaCheckedList.splice(otherIndex, 1)
        areaCheckedList = [...areaCheckedList, ...(areaMap['外地'] || [])]
      }
      const foreignIndex = areaCheckedList.indexOf('外籍')
      if (foreignIndex !== -1) {
        areaCheckedList.splice(foreignIndex, 1)
        areaCheckedList = [...areaCheckedList, ...(areaMap['外籍'] || [])]
      }
      condition.push({ k: 'area', o: 'in', v: areaCheckedList.join(',') })
    }
    if (typeCheckedList.length) {
      condition.push({ k: 'occupation', o: 'in', v: typeCheckedList.join(',') })
    }
    if (form.name !== undefined && form.name !== '') {
      condition.push({ k: 'name', o: 'like', v: `%${form.name}%` })
    }
    if (form.retire !== undefined && form.retire !== '') {
      condition.push({ k: 'retire', o: '=', v: form.retire })
    }
    if (form.foreign_case_in !== undefined && form.foreign_case_in !== '') {
      condition.push({ k: 'foreign_case_in', o: '=', v: form.foreign_case_in })
    }
    if (form.gender !== undefined && form.gender !== '') {
      condition.push({ k: 'gender', o: '=', v: form.gender })
    }
    if (form.cause_action !== undefined && form.cause_action !== '') {
      condition.push({ k: 'cause_action', o: 'like', v: `%${form.cause_action}%` })
    }
    if (form.professional !== undefined && form.professional !== '') {
      condition.push({ k: 'professional', o: 'like', v: `%${form.professional}%` })
    }
    this.setState({ condition })
    const data = {
      current,
      page_size: pageSize,
      status,
      condition: JSON.stringify(condition)
    }
    if (orderField && order) {
      data.order = order === 'ascend' ? 'asc' : 'desc'
      data.order_field = orderField
    }
    return data
  }

  // 获取案件数据
  getTableData (form) {
    const { pagination } = this.state
    const { current, pageSize } = pagination
    this.setState({ loading: true })
    this.$get('/api/xapc/arbitratorcase', this.getParams(form)).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 获取案由
  getTreeData () {
    this.$get('/api/common/cause_action')
      .then(res => {
        if (res.status === 1 && res.data instanceof Array) {
          this.setState({ treeData: res.data })
        }
      })
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters, sorter) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order,
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      areaCheckAll: true,
      typeCheckAll: true,
      detailAreaVisible: false,
      areaCheckedList: this.state.areaOptions.slice(),
      typeCheckedList: this.state.typeOptions.slice(),
      actions: undefined,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 格式化所在区域
  formatArea (data) {
    const keys = Object.keys(data)
    let result = []
    keys.forEach(key => {
      result = [...result, ...data[key]]
    })
    this.setState({
      detailAreaOptions: result,
      areaCheckedList: this.state.areaOptions.slice(),
      areaMap: data
    })
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 从字典中获取仲裁员类型
  getTypeFromDictionary () {
    return this.$get('/api/xapc/dictionary', {
      types: '仲裁员职业分类'
    }).then(res => {
      if (res.status === 1) {
        // 设置枚举字典
        const dictionaries = this.formatDictionaries(res.data)
        const typeOptions = (dictionaries['仲裁员职业分类'] || []).map(li => li.title)
        this.setState({
          occupationMap: dictionaries['仲裁员职业分类'],
          typeOptions,
          typeCheckedList: typeOptions.slice()
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 获取所在区域
  getAreaMap () {
    return this.$get('/api/xapc/arbitrator/area')
      .then(res => {
        if (res.status === 1) {
          this.formatArea(res.data)
        } else {
          message.warning(res.message)
        }
      })
  }

  // 获取专业
  getDictionary () {
    return this.$get('/api/xapc/dictionary', {
      types: '专业'
    }).then(res => {
      if (res.status === 1) {
        this.setState({
          majors: res.data[0].list.map(li => li.value)
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 改变多选项
  changeCheckbox (type, list) {
    const options = this.state[type + 'Options']
    this.setState({
      [type + 'CheckedList']: list,
      [type + 'Indeterminate']: !!list.length && list.length < options.length,
      [type + 'CheckAll']: list.length === options.length
    })
  }

  // 点击全选按钮
  changeAll (type, e) {
    this.setState({
      [type + 'CheckedList']: e.target.checked ? this.state[type + 'Options'] : [],
      [type + 'Indeterminate']: false,
      [type + 'CheckAll']: e.target.checked
    })
  }

  // 改变选中项
  onSelectChange = selectedRowKeys => {
    const { current, pageSize } = this.state.pagination
    const i = selectedRowKeys[0] - (current - 1) * pageSize
    const o = this.state.list[i]
    if (this.props.disabledIdList.indexOf(o.id) !== -1) {
      return false
    }
    this.setState({ selectedRowKeys }, () => {
      this.props.onChange({ arbitrator: o.name, arbitratorid: o.id })
    })
  }

  // 全选区域
  changeAllArea (e) {
    const options = this.state.detailAreaVisible ? this.state.detailAreaOptions : this.state.areaOptions
    this.setState({
      areaCheckedList: e.target.checked ? options : [],
      areaIndeterminate: false,
      areaCheckAll: e.target.checked
    })
  }

  // 改变区域多选项
  changeAreaCheckbox (list) {
    const options = this.state.detailAreaVisible ? this.state.detailAreaOptions : this.state.areaOptions
    this.setState({
      areaCheckedList: list,
      areaIndeterminate: !!list.length && list.length < options.length,
      areaCheckAll: list.length === options.length
    })
  }

  // 展开详细区域
  showDetailArea () {
    this.setState({
      detailAreaVisible: true
    }, () => {
      if (this.state.areaCheckAll) {
        this.changeAreaCheckbox(this.state.detailAreaOptions)
      } else {
        let list = []
        const checkedList = this.state.areaCheckedList
        const areaMap = this.state.areaMap
        const areaList = ['哈尔滨市', '齐齐哈尔市', '牡丹江市', '佳木斯市', '大庆市', '鸡西市', '双鸭山市', '鹤岗市', '七台河市', '伊春市', '黑河市', '绥化市', '大兴安岭地区']
        areaList.forEach(li => {
          if (checkedList.indexOf(li) !== -1) {
            list.push(li)
          }
        })
        if (checkedList.indexOf('外地') !== -1) {
          list = [...list, ...(areaMap['外地'] || [])]
        }
        if (checkedList.indexOf('外籍') !== -1) {
          list = [...list, ...(areaMap['外籍'] || [])]
        }
        this.changeAreaCheckbox(list)
      }
    })
  }

  // 隐藏详细区域
  hideDetailArea () {
    this.setState({
      detailAreaVisible: false
    }, () => {
      if (this.state.areaCheckAll) {
        this.changeAreaCheckbox(this.state.areaOptions)
      } else {
        const list = []
        const checkedList = this.state.areaCheckedList
        const areaMap = this.state.areaMap
        const hasOther = (areaMap['外地'] || []).every(a => checkedList.indexOf(a) !== -1)
        const hasForeign = (areaMap['外籍' || []]).every(a => checkedList.indexOf(a) !== -1)
        const areaList = ['哈尔滨市', '齐齐哈尔市', '牡丹江市', '佳木斯市', '大庆市', '鸡西市', '双鸭山市', '鹤岗市', '七台河市', '伊春市', '黑河市', '绥化市', '大兴安岭地区']
        areaList.forEach(li => {
          if (checkedList.indexOf(li) !== -1) {
            list.push(li)
          }
        })
        if (hasOther) {
          list.push('外地')
        }
        if (hasForeign) {
          list.push('外籍')
        }
        this.changeAreaCheckbox(list)
      }
    })
  }

  // 获取基础数据
  getBaseData () {
    Promise.all([this.getAreaMap(), this.getTypeFromDictionary(), this.getDictionary()])
      .then(() => {
        setTimeout(() => {
          this.getTableData()
        }, 0)
      })
  }

  // 设置要修改的仲裁员详情
  modifyDetail (l) {
    l = _.cloneDeep(l)
    this.setState({
      detailData: l,
      detailVisible: true
    }, () => {
      setTimeout(() => {
        l.professional = l.professional ? l.professional.split(',') : []
        l.cause_action = l.cause_action ? l.cause_action.split(',') : []
        const keys = Object.keys(l)
        keys.forEach(key => {
          if (l[key] === null) {
            l[key] = undefined
          }
        })
        this.detailFormRef.current.setFieldsValue(l)
      }, 100)
    })
  }

  // 更新仲裁员详情
  updateDetail (d) {
    const hide = message.loading('更新中', 120)
    d.professional = d.professional.join()
    d.cause_action = d.cause_action.join()
    compressLicenseAndMobile(d)
    this.$put(`/api/xapc/arbitrator/${d.id}`, d)
      .then(res => {
        hide()
        if (res.status === 1) {
          this.setState({
            detailData: null,
            detailVisible: false
          }, () => {
            this.getTableData()
          })
        } else {
          message.warning(res.message)
        }
      })
      .catch(() => hide())
  }

  downloadExcel () {
    const h = message.loading('导出中', 120)
    this.$get('/api/xapc/arbitratorcase', { condition: JSON.stringify(this.state.condition), page_size: 10000, current: 1 }).then(res => {
      h()
      this.setState({ loading: false })
      if (res.status === 1) {
        const list = res.data.list.map((l, i) => {
          const o = {
            序号: i + 1,
            姓名: l.name,
            专业: l.professional,
            单位: l.structure,
            职业分类: l.occupation,
            擅长专业: l.special,
            总办: l.caseon_all,
            在办: l.caseing,
            今年总办: l.caseon,
            首: l.caseon1,
            独: l.caseon2,
            边: l.caseon3
          }
          if (this.state.actions) {
            o.同案由 = l.cause_action_count
          }
          return o
        })
        json2Excel([{ data: list, sheetname: '仲裁员案件统计' }], '仲裁员案件统计')
      } else {
        return message.warning(res.message)
      }
    }).catch(() => { h() })
  }

  componentDidMount () {
    this.getTreeData()
    this.getBaseData()
  }

  render () {
    const columns = getColumns.call(this)
    const initialValues = { foreign_case_in: '', retire: '' }
    return (
      <div className={style.container}>
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} ref={this.formRef} initialValues={initialValues} onFinish={v => this.searchHandle(v)}>
              <Row>
                <Col span={8}>
                  <Item label='名称' name='name'>
                    <Input placeholder='请输入名称' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='工作状况' name='retire'>
                    <Select placeholder='请选择工作状况'>
                      <Option value=''>全部</Option>
                      <Option value={1}>在职</Option>
                      <Option value={0}>非在职</Option>
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='擅长涉外' name='foreign_case_in'>
                    <Select placeholder='请选择擅长涉外'>
                      <Option value=''>全部</Option>
                      <Option value={1}>是</Option>
                      <Option value={0}>不是</Option>
                    </Select>
                  </Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Item label='案由' name='cause_action'>
                    <TreeSelect
                      style={{ width: '100%' }}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      treeData={this.state.treeData}
                      placeholder='请选择案由'
                      showSearch
                      onChange={d => { this.setState({ actions: d }) }}
                    />
                  </Item>
                </Col>
                <Col span={12}>
                  <Item label='专业' name='professional'>
                    <Select className={style.full} placeholder='请选择专业' showSearch allowClear>
                      {
                        this.state.majors.map(li => <Option key={li} value={li}>{li}</Option>)
                      }
                    </Select>
                  </Item>
                </Col>
              </Row>
              <Item label='所在区域'>
                <div>
                  <Checkbox
                    indeterminate={this.state.areaIndeterminate}
                    onChange={e => this.changeAllArea(e)}
                    checked={this.state.areaCheckAll}
                    style={{ marginTop: '5px' }}
                  >全选
                  </Checkbox>
                  {this.state.detailAreaVisible ? (
                    <>
                      <div className={style['detail-area']}>
                        <Checkbox.Group
                          options={this.state.detailAreaOptions}
                          value={this.state.areaCheckedList}
                          onChange={v => this.changeAreaCheckbox(v)}
                        />
                        <Button type='link' onClick={() => this.hideDetailArea()}>收起</Button>
                      </div>
                    </>
                  ) : (
                    <>
                      <Checkbox.Group
                        options={this.state.areaOptions}
                        value={this.state.areaCheckedList}
                        onChange={v => this.changeAreaCheckbox(v)}
                      />
                      <Button type='link' onClick={() => this.showDetailArea()}>更多</Button>
                    </>
                  )}
                </div>
              </Item>
              <Item label='职业分类'>
                <div>
                  <Checkbox
                    indeterminate={this.state.typeIndeterminate}
                    onChange={e => this.changeAll('type', e)}
                    checked={this.state.typeCheckAll}
                  >全选
                  </Checkbox>
                  <Checkbox.Group
                    options={this.state.typeOptions}
                    value={this.state.typeCheckedList}
                    onChange={v => this.changeCheckbox('type', v)}
                  />
                </div>
              </Item>
              <Row gutter={24}>
                <Item className={style['right-line']}>
                  <Space size='middle'>
                    <Button type='primary' ghost htmlType='submit'>搜索</Button>
                    <Button htmlType='reset' onClick={() => this.resetHandle()}>重置</Button>
                  </Space>
                </Item>
              </Row>
            </Form>
          </div>
        </div>

        <div className={style['table-container']}>
          <div className={style['operate-line']}>
            <Button icon={<DownloadOutlined />} onClick={() => confirmAction('您确定要导出excel吗？', () => this.downloadExcel())}>导出excel</Button>
          </div>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(ArbitratorCaseStatistic)
